package cn.lzj.ymcc.controller;

import cn.lzj.ymcc.constants.OssContants;
import cn.lzj.ymcc.result.JSONResult;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController
@RequestMapping("/oss")
public class OssController {
    @GetMapping("/sign")
    public JSONResult osstoSign(){
        OSSClient client = new OSSClient(OssContants.OSS_ACCESS_ENDPOINT,
                OssContants.OSS_ACCESSID_CODE, OssContants.OSS_ACCESSKEY_CODE);
        try {
            long expireTime = OssContants.OSS_ACCESS_DIR_EXPRISETIME;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, OssContants.OSS_ACCESS_DIR_PREFIX);

            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = client.calculatePostSignature(postPolicy);

            Map<String, String> respMap = new LinkedHashMap<String, String>();
            respMap.put("accessid", OssContants.OSS_ACCESSID_CODE);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", OssContants.OSS_ACCESS_DIR_PREFIX);
            respMap.put("host", OssContants.OSS_ACCESS_HOST);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
            // respMap.put("expire", formatISO8601Date(expiration));
            return JSONResult.success(respMap);

        } catch (Exception e) {
            // Assert.fail(e.getMessage());
            System.out.println(e.getMessage());
            return JSONResult.error("获取签名失败！！");
        }
    }
}
